<?php
/**
 * Created by PhpStorm.
 * User: sky
 * Date: 2019/7/16
 * Time: 23:04
 */

namespace App\Repositories;

use App\Models\Goods;
use App\Models\GoodsItems;
use App\Models\GoodsParames;

class GoodsRepositories
{
    public function model()
    {
        return Goods::query();
    }

    public function find($id)
    {
        return $this->model()->with(['goodsItems','manyCategory','manyImages'])->where('id',$id)->first();
    }

    public function save($data)
    {
        //dd($data);
        //对参数进行过滤
        if(isset($data['params']) && !empty($data['params']))
        {
            $params     = [];
            foreach ($data['params'] as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $vk => $vv) {
                        $params[$key][] = $vk;
                    }
                } elseif ($val !== '') {
                    $params[$key] = $val;
                }
            }
            $data['params'] =serialize($params);
        }
        //对规格进行处理
        if(isset($data['attributes']) && !empty($data['attributes']))
        {
            $data['spes_desc'] =serialize($data['attributes']);
        }

        $goods = $this->model()->create($data);

        if(isset($data['category_id']) && !empty($data['category_id']))
        {
            $categoryId =explode(',',$data['category_id']);
            $goods->manyCategory()->sync($categoryId);
        }
        $firstImagesId='';
        if(isset($data['images']) && !empty($data['images']))
        {
            //$imgagesId =explode(',',$data['imgages']);
            $firstImagesId =$data['images'][0];
            $imagesId = [];
            foreach ($data['images'] as $key =>$val)
            {
                $imagesId[$val]=['sort'=>$key];
            }
            $goods->manyImages()->sync($imagesId);
        }
        //是否开启多规格
        $spesArr=[];
        if(isset($data['open_attributes']) && $data['open_attributes'] == 1)
        {
            //todo
            $i=0;
            foreach ($data['item'] as $key =>$val)
            {
                if(isset($data['is_defalut']) && !empty($data['is_defalut']))
                {
                    $isDefalut=$data['is_defalut'];
                }
                else{
                    $isDefalut=($i==0)?1:0;
                }
                $spesArr[] =[
                    'goods_id'=>$goods->id,
                    'price'=>$data['price'],
                    'costprice'=>$data['costprice'],
                    'market_price'=>$data['market_price'],
                    'sn'=>$data['sn'],
                    'stock'=>$data['stock'],
                    'barcode'=>isset($data['barcode'])?$data['barcode']:null,
                    'image_id'=>isset($data['image_id'])?$data['image_id']:null,
                    'is_defalut'=>$isDefalut,
                ];
                $i++;
            }
        }
        else
        {
            //todo
            $spesArr=[
                'goods_id'=>$goods->id,
                'price'=>$data['price'],
                'costprice'=>$data['costprice'],
                'market_price'=>$data['market_price'],
                'sn'=>$data['sn'],
                'stock'=>$data['stock'],
                'barcode'=>isset($data['barcode'])?$data['barcode']:null,
                'image_id'=>$firstImagesId,
                'is_defalut'=>1,
            ];
        }
        GoodsItems::insert($spesArr);
        return $goods;
    }

    public function update($id,$data)
    {
        $updateData=[
            'name'=>$data['name'],
            'slug'=>$data['slug'],
            'goods_type_id'=>$data['goods_type_id'],
            'brand_id'=>$data['brand_id'],
            'bn'=>isset($data['bn'])?$data['bn']:null,
            'summary'=>isset($data['summary'])?$data['summary']:null,
            'weight'=>isset($data['weight'])?$data['weight']:null,
            'unit'=>isset($data['unit'])?$data['unit']:null,

            'spes_desc'=>isset($data['spes_desc'])?$data['spes_desc']:null,
            'params'=>isset($data['params'])?$data['params']:null,

            'post_content'=>$data['post_content'],
            'is_recommend'=>isset($data['is_recommend'])?$data['is_recommend']:0,
            'is_hot'=>isset($data['is_hot'])?$data['is_hot']:0,

            'meta_title'=>isset($data['meta_title'])?$data['meta_title']:null,
            'meta_keywords'=>isset($data['meta_keywords'])?$data['meta_keywords']:null,
            'meta_description'=>isset($data['meta_description'])?$data['meta_description']:null,

        ];
        $goods =$this->find($id);
        if($goods->update($updateData))
        {
            if(isset($data['category_id']) && !empty($data['category_id']))
            {
                $categoryId =explode(',',$data['category_id']);
                $goods->manyCategory()->sync($categoryId);
            }

            if(isset($data['images']) && !empty($data['images']))
            {
                $imagesId = [];
                foreach ($data['images'] as $key =>$val)
                {
                    $imagesId[$val]=['sort'=>$key];
                }
                $goods->manyImages()->sync($imagesId);
            }

            return true;
        }

        return false;
    }

    public function search($data)
    {
        $model = $this->model()->with(['manyImages','manyCategory','goodsItems']);

        if(isset($data['name']))
        {
            $model = $model->where('name','like','%'.$data['name'].'%');
        }

        $data['limit'] = isset($data['limit'])?$data['limit']:999;

        //些处扩展更多查询条件
        return $model->orderBy('created_at','desc')->paginate($data['limit'])->toArray();
    }

    public function delete($ids)
    {
        return Goods::destroy($ids);
    }

    public function getItemsByGoodsId($goodsId)
    {
        return GoodsItems::where('goods_id',$goodsId)->get();
    }

}